package cn.shenlong.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import java.util.List;
import org.apache.commons.lang.StringUtils;

public class FileUtil {

	/**
	 * 获取某个文件夹下的文件，只取得向下一级
	 * 
	 * @param dirStr
	 * @return
	 */
	public static List<File> getFiles(String dirStr) throws Exception {
		List<File> fileList = new ArrayList<File>();
		if (StringUtils.isBlank(dirStr)) {
			return fileList;
		}
		File[] files = null;
		try {
			File dir = new File(dirStr);
			files = dir.listFiles();
		} catch (Exception e) {
			throw e;
		}
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				fileList.add(files[i]);
			}
		}

		return fileList;
	}

	/**
	 * 获取某个文件夹下的html文件，包括文件夹下的文件夹
	 * 
	 * @param dirStr
	 * @return
	 */
	public static List<File> getAllFiles(String dirStr) throws Exception {
		List<File> fileList = new ArrayList<File>();
		if (StringUtils.isBlank(dirStr)) {
			return fileList;
		}
		File[] files = null;
		try {
			File dir = null;

			dir = new File(dirStr);
			if (!dir.exists()) {
				// 当前路径找不到时！
				throw new Exception("读取" + dirStr + "路径时，发生异常");
			}
			if (dir.isDirectory() == false) {
				fileList.add(dir);
			} else {
				files = dir.listFiles();
				if (files != null && files.length > 0) {
					for (int i = 0; i < files.length; i++) {
						if (files[i].isDirectory() == true) {

							List<File> tmp = getAllFiles(files[i].getPath());
							fileList.addAll(tmp);
						} else {
							fileList.add(files[i]);
						}

					}
				}
			}

		} catch (Exception e) {
			throw e;
		}
		return fileList;
	}

	/**
	 * 获取文件的文本内容
	 * 
	 * @param file
	 * @return
	 */
	public static String getFileContent(File file) throws Exception {
		if (file == null) {
			return "";
		}
		String strs = "";
		try {
			FileInputStream fis = new FileInputStream(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			String tmp = "";
			StringBuffer sf = new StringBuffer();
			while ((tmp = br.readLine()) != null) {
				sf.append(tmp);
			}
			strs = sf.toString();
		} catch (Exception e) {
			throw e;
		}

		return strs;
	}

	/**
	 * 通用删除文件方法
	 * 
	 * @param url
	 */
	public static void deleteFile(String url) {
		if (StringUtils.isBlank(url)) {
			return;
		} else {
			File file = new File(url);
			// 判断目录或文件是否存在
			if (!file.exists()) { // 不存在返回
				return;
			} else {

				file.delete();

			}
		}

	}

}
